#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author  : config_spider
import json
import math

import scrapy
import re
from apps.tax_policy.tax_policy.items import NetTaxPolicyItem as Item, urllib, time
from apps.tax_policy.tax_policy.spiders.base_spider.base_tax_policy_spider import BaseTaxPolicySpider


class HenanZhumadianPolicy(BaseTaxPolicySpider):
    name = 'henan_zhumadian1_policy'
    
    province = '河南省'
    city = '驻马店市'
    # county = '滑县'
    park = ''

    custom_settings = {
        "DOWNLOAD_TIMEOUT": 60
    }
    headers = {
        "Accept": "application/json, text/javascript, */*; q=0.01",
        "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
        # "X-Requested-With": "XMLHttpRequest"
    }

    def start_requests(self):
        for source, county, url in [
            ['驻马店市平舆县人民政府', "平舆县", "http://www.pingyu.gov.cn/xxgkContent/?branch_id=5417e7499a05c26641f6e0d5&column_code=40100&topic_id="],
            ['驻马店市平舆县人民政府', "平舆县", "http://www.pingyu.gov.cn/xxgkContent/?branch_id=5417e7499a05c26641f6e0d5&column_code=40200&topic_id="],
        ]:
            item = {'source': source, 'county': county}
            yield scrapy.Request(url, callback=self.parse_list, meta={'item': item}, dont_filter=True)

    def parse_list(self, response, **kwargs):
        prev_item = response.meta.get('item')
        elem_list = response.xpath(
            "//div[@class='list-info-one' or @class='msg_li' or @class='hap_infoOne']//a[(contains(@href, '.htm') or @title)]/parent::div[string-length(string(.))>=10] | "
            "//ul//li[@class='colRightOne']//a[(contains(@href, '.htm') or @title)]/parent::li[string-length(string(.))>=10] | "
            "//tr[@class]//td//a[(contains(@href, '.htm') or @title)]/parent::td[string-length(string(.))>=10] | "
            "//section[@class='m-tglist f-mb25 f-md-mb15']//li//a[(contains(@href, '.htm') or @title)]/parent::li[string-length(string(.))>=10] | "
            "//ul[contains(@class, 'ul ULLIST') or @class='infoList']//li//a[@class]/ancestor::li[string-length(string(.))>=10]"
        )
        for elem in elem_list:
            item = Item()
            item['source_url'] = elem.xpath(""".//a/@href""").get()
            item['source_url'] = response.urljoin(item['source_url'])
            item['publish_date'] = elem.xpath("""string(.)""").get()
            if prev_item is not None:
                for key, value in prev_item.items():
                    item[key] = value
            if not item['source_url']:
                continue
            # if '.htm' not in item['source_url'] and '.shtm' not in item['source_url']:
            #     continue
            if 'relativeInfo' in item['source_url']:
                continue
            print(response.url, item['source_url'])
            yield response.follow(item['source_url'], callback=self.parse_detail, meta={'item': item})
        if response.meta.get("is_next") is not False:
            pages = response.xpath("//pagination/@pagecount").get() or 0
            print(f"{response.url} {pages}")
            for page_num in range(2, int(pages)+1):
                url = f"{response.url}" + f'&page={page_num}'
                yield response.follow(url, callback=self.parse_list, meta={'item': prev_item, 'is_next': False})

    def parse_detail(self, response, **kwargs):
        item = Item() if response.meta.get('item') is None else response.meta.get('item')
        item['title'] = response.xpath("""string(//meta[@name='ArticleTitle']/@content)""").get()
        item['publish_date'] = response.xpath("""string(//meta[@name='PubDate']/@content)""").get().split(' ')[0]
        item['content'] = response.xpath(""".""").get()
        # item['source'] = self.source
        item['province'] = self.province
        item['city'] = self.city
        # item['county'] = self.county
        item['park'] = self.park
        yield item


if __name__ == "__main__":
    from scrapy import cmdline

    cmdline.execute("scrapy crawl henan_zhumadian1_policy".split())
